package cv.ltq.studentesdemo.controller;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.CompletionSuggest;
import co.elastic.clients.elasticsearch.core.search.CompletionSuggester;
import co.elastic.clients.elasticsearch.core.search.FieldSuggester;
import co.elastic.clients.elasticsearch.core.search.Suggester;
import co.elastic.clients.util.ObjectBuilder;
import com.fasterxml.jackson.databind.ObjectMapper;
import cv.ltq.studentesdemo.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

@Controller
public class StudentSearchController {
    @Autowired
    ElasticsearchClient client;
    private CompletionSuggest.Builder builder;

    @GetMapping("/studentSearch") //路由到添加新书页面
    public String addStudent(){
        return "studentSearch";
    }

    @GetMapping("/autocomplete") //自动补全查询
    @ResponseBody
    public String autocomplete(String prefix) throws IOException {
        List<Student> list=new ArrayList<>();
        builder = new CompletionSuggest.Builder();
        FieldSuggester fieldSuggester = new FieldSuggester.Builder()//获取要搜索的文字
                .prefix(prefix)
                .completion(new CompletionSuggester.Builder().field("university").size(2).build())
                .build();

        SearchRequest searchRequest=new SearchRequest.Builder()
                .index("student")
                .suggest(new Suggester.Builder().suggesters("autocomplete_sugger",fieldSuggester).build())
                .build();

        SearchResponse<Student> search = client.search(searchRequest, Student.class);

        int size=search.suggest().get("autocomplete_sugger")
                .get(0)
                .completion().options().size();//查出来的结果条数

        for (int i=0;i<size;i++){
            Student student=search.suggest().get("autocomplete_sugger")
                    .get(0).completion().options().get(i).source();
            list.add(student);
        }
        ObjectMapper objectMapper=new ObjectMapper();
        return objectMapper.writeValueAsString(list);
    }
}
